/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.florent37.github.com.expansionpanel.viewgroup;

import com.florent37.github.com.expansionpanel.ExpansionLayout;

import java.util.Collection;
import java.util.HashSet;

/**
 * lipeiquan
 *
 * @since 2021-05-06
 */
public class ExpansionLayoutCollection {

    private final Collection<ExpansionLayout> expansions = new HashSet<>();
    private boolean openOnlyOne = true;

    private final ExpansionLayout.IndicatorListener indicatorListener = new ExpansionLayout.IndicatorListener() {
        @Override
        public void onStartedExpand(ExpansionLayout expansionLayout, boolean willExpand) {
            if (willExpand && openOnlyOne) {
                for (ExpansionLayout view : expansions) {
                    if (view != expansionLayout) {
                        view.collapse(true);
                    }
                }
            }
        }
    };

    public ExpansionLayoutCollection add(ExpansionLayout expansionLayout) {
        expansions.add(expansionLayout);
        expansionLayout.addIndicatorListener(indicatorListener);
        return this;
    }

    public ExpansionLayoutCollection addAll(ExpansionLayout... expansionLayouts) {
        for (ExpansionLayout expansionLayout : expansionLayouts) {
            if (expansionLayout != null) {
                add(expansionLayout);
            }
        }
        return this;
    }

    public ExpansionLayoutCollection addAll(Collection<ExpansionLayout> expansionLayouts) {
        for (ExpansionLayout expansionLayout : expansionLayouts) {
            if (expansionLayout != null) {
                add(expansionLayout);
            }
        }
        return this;
    }

    public ExpansionLayoutCollection remove(ExpansionLayout expansionLayout) {
        if (expansionLayout != null) {
            expansions.remove(expansionLayout);
            expansionLayout.removeIndicatorListener(indicatorListener);
        }
        return this;
    }

    public ExpansionLayoutCollection openOnlyOne(boolean openOnlyOne) {
        this.openOnlyOne = openOnlyOne;
        return this;
    }
}
